import { toCsvString } from '../../utils/csv';
import { showErrorToast, showSuccessToast } from '../../utils/toast';
import { cardT, historyT, parseCardResult, cardKeyword, cardDescript, cardsT } from './types'

// pages/text_ocr/ocr.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pickerVisible: false,
    pickerValue: ["idCard"],
    pickerText: "身份证",
    cardType: "idCard",
    btnText: "",
    idtypes: [
      { label: "身份证", value: "idCard" },
      { label: "银行卡", value: "bankCard" },
      { label: "驾驶证", value: " driverslicense" },
      { label: "行驶证", value: "drivingLicense" }, 
      { label: "营业执照", value: "businessLicense" },
      { label: "车牌", value: "platenum" },
      { label: "菜单", value: "menu" },
    ],
    popVisible: false,
    imageViewVisible: false,
    resultKeys: [] as string[],
    result:  null as cardT,
    historyStorageKey: 'text-ocr-history',
    history: [] as historyT[],
  },

  onPicker() {
    this.setData({
      pickerVisible: true,
    })
  },

  onPickerChange(e: WechatMiniprogram.CustomEvent) {
    let { label, value } = e.detail
    this.setData({
      pickerVisible: false,
      pickerValue: value,
      pickerText: label.join(' '),
    });
    this.setCardType()
    this.setBtnText()
  },

  onPickerCancel() {
    this.setData({
      pickerVisible: false,
    });
  },
  
  // 设置当前选择的卡类型
  setCardType() {
    this.setData({
      cardType: this.data.pickerValue[0],
    })
  },

  // 设置picker 呼起按钮后显示的卡片类型
  setBtnText() {
    let cardType = ''
    this.data.idtypes.forEach(item => {
      if (item.value == this.data.cardType) {
        cardType = item.label
      }
    });
    this.setData({
      btnText: `${cardType}识别`,
    })
  },

  // 卡片识别成功
  cardResult(e: WechatMiniprogram.CustomEvent) {
    console.log(e)
    let result = parseCardResult(e)
    if (!result) {
      showErrorToast(this, '结果解析失败')
      return
    }
    console.log(result)
    this.setResult(result)
  },

  // 更新识别结果，写入本地历史，呼起详情弹层
  setResult(result: cardT, addHistory: boolean = true, pop: boolean = true) {
    if (!result) {
      return;
    }
    let change:any = {
      resultKeys: this.getResultKeys(result),
      result: result,
      popVisible: pop,
    }
    if (addHistory) {
      let history = (this.data.history || [])
      history.unshift({
        card: result,
        keyword: cardKeyword(result),
        descript: cardDescript(result),
      })
      change.history = history
    }
    this.setData(change)
    this.appendHistoryRecord(result)
  },

  // 追加新的历史记录，忽略错误信息
  appendHistoryRecord(result: cardT) {
    let append = (data: cardT[]) => {
      data.unshift(result)
      wx.setStorage({
        key: this.data.historyStorageKey,
        data: data,
      })
    }
    wx.getStorage({
      key: this.data.historyStorageKey,
      success:  (res) => {
        let data = res.data as cardsT  || []
        append(data)
      },
      fail: () => {
        append([])
      }
    })
  },

  // 历史记录点击呼起详情弹层
  onRecord(e: WechatMiniprogram.CustomEvent) {
    let result  = e.currentTarget.dataset['item']?.card as cardT;
    this.setData({
      resultKeys: this.getResultKeys(result),
      result: result,
      popVisible: true,
      popImageVisible: false,
    })
  },

  // 详情弹层隐藏时的回调
  onPopVisibleChange(e: WechatMiniprogram.CustomEvent) {
    let { visible } = e.detail
    this.setData({
      popVisible: visible,
    })
  },

  // image view
  onRecordImage(e: WechatMiniprogram.CustomEvent) {
    let result  = e.currentTarget.dataset['item']?.card as cardT;
    this.setData({
      result: result,
      popVisible: false,
      imageViewVisible: true,
    })
  },

  onImageViewClose() {
    this.setData({
      imageViewVisible: false,
    })
  },

  // 用于详情弹层显示的结果keys
  getResultKeys(result: cardT): string[] {
    if (!result) {
      return []
    }
    let keys = Object.keys(result)
    let validKeys: string[] = []
    keys.forEach(item => {
      if (item == '_type' || item == 'image_path') {
        return
      }
      validKeys.push(item)
    })
    return validKeys
  },

  // 复制结果
  onResultCopy() {
    if (!this.data.result) {
      showErrorToast(this, '没有找到需要复制的数据')
      return
    }
    let result = this.data.result as Record<string, string|number>
    let pices: string[] = []
    this.data.resultKeys.forEach(item => {
      if (!!result[item]) {
        pices.push(`${result[item]}`)
      }
    })

    wx.setClipboardData({
      data: pices.join("\n"),
      success: () => {
      }
    })
  },

  // 下载所有历史记录
  onDownloadHistory() {
    if (this.data.history.length <= 0) {
      return
    }

    let cards: cardT[] = []
    this.data.history.forEach(item => {
      cards.push(item.card)
    })

    let data = toCsvString(cards)
    let path = `${wx.env.USER_DATA_PATH}/微信小工具_ocr.csv`
    let fs = wx.getFileSystemManager()
    fs.writeFile({
      filePath: path,
      data: data,
      encoding: 'utf8',
      success: () => {
        // 下载后打开另存到本地
        wx.openDocument({
          filePath: path,
          fileType: 'xlsx',
          success: function () {
            console.log('打开文档成功')
          }
        })
      },
      fail: (res) => {
        showErrorToast(this, `保存失败 ${res}`)
      }
    })
  },

  // 清空所有历史记录
  onClearHistory() {
    wx.setStorage({
      key: this.data.historyStorageKey,
      data: [],
      success: () => {
        this.setData({
          resultKeys: [],
          result: null,
          history: [],
        })
        showSuccessToast(this, '历史记录已清空')
      },
      fail: (e) => {
        showErrorToast(this, `清除历史记录失败 ${e}`)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    wx.getStorage({
      key: this.data.historyStorageKey,
      success: (res) => {
        let data = res.data as cardsT
        if (!data) {
          return
        }

        let history: historyT[] = []
        data.forEach(item => {
          history.push({
            card: item,
            keyword: cardKeyword(item),
            descript: cardDescript(item),
          })
        })

        this.setData({
          history: history,
        })
      }
    })

    // this.setData({
    //   history: testHistory(),
    // })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})